package com.itheima.servcie;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.itheima.bean.CodeBean;
import com.itheima.dbservice.UserInfoServiceApi;
import com.itheima.exception.CommonException;
import com.itheima.pojo.UserInfo;
import com.itheima.template.OssTemplate;
import com.itheima.utils.RandomUtil;
import com.itheima.vo.VoiceVo;
import com.sun.org.apache.bcel.internal.classfile.Code;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class PeachblossomService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private OssTemplate ossTemplate;
    @DubboReference
    private UserInfoServiceApi userInfoServiceApi;

    public void send(MultipartFile soundFile) {
        try {
            //获取当前用户id
            Long uid = Convert.toLong(stringRedisTemplate.opsForValue().get(CodeBean.ID));
            //上传音频到阿里云并返回路径
            String voicePath = ossTemplate.upload(soundFile.getOriginalFilename(), soundFile.getInputStream());
            log.info(voicePath);
            //将路径存入Redis
            stringRedisTemplate.opsForValue().set(CodeBean.VOICE_USER + uid, voicePath);

            //将用户id存入Redis集合中（判断id是否已存在）
            String list = stringRedisTemplate.opsForValue().get(CodeBean.VOICE_USERIDS);
            //判断是否为空
            if (ObjectUtil.isNotNull(list)) {
                //json解析
                List<Long> ids = JSONUtil.toList(JSONUtil.parseArray(list), Long.class);
                //判断id是否已存在,不存在则添加，存在则不添加
                if (!ids.contains(uid)) {
                    ids.add(uid);
                }
                //重新存入Redis中
                stringRedisTemplate.opsForValue().set(CodeBean.VOICE_USERIDS, JSONUtil.toJsonStr(ids));
            } else {
                //为空则创建集合
                List<Long> ids = new ArrayList<>();
                ids.add(uid);
                //存入Redis
                stringRedisTemplate.opsForValue().set(CodeBean.VOICE_USERIDS, JSONUtil.toJsonStr(ids));
            }
        } catch (IOException e) {
            log.error(e.getMessage());
        }
    }

    public VoiceVo receive() {
        //获取当前用户id
        Long uid = Convert.toLong(stringRedisTemplate.opsForValue().get(CodeBean.ID));
        //随机从Redis中取id
        String list = stringRedisTemplate.opsForValue().get(CodeBean.VOICE_USERIDS);
        //判断是否为null
        if (ObjectUtil.isNull(list)) {
            throw new CommonException("暂无音频");
        }
        List<Long> ids = JSONUtil.toList(JSONUtil.parseArray(list), Long.class);
        //随机取出一个id
        List<Long> id = RandomUtil.createRandoms(ids, 1);
        //查询Redis对应音频
        String path = stringRedisTemplate.opsForValue().get(CodeBean.VOICE_USER + id.get(0));
        //查询对应用户信息
        UserInfo userInfo = userInfoServiceApi.getUserInfoById(id.get(0));
        //判断剩余机会
        Integer userChance = 0;
        String chance = stringRedisTemplate.opsForValue().get(CodeBean.VOICE_USER_CHANCE + uid);
        if (ObjectUtil.isNull(chance)) {
            stringRedisTemplate.opsForValue().set(CodeBean.VOICE_USER_CHANCE + uid, "1", 5, TimeUnit.MINUTES);
        } else {
            userChance = Convert.toInt(chance);
            if (userChance > 3) {
                throw new CommonException("您今日的次数已用完！");
            } else {
                //次数+1并再次存入
                stringRedisTemplate.opsForValue().set(CodeBean.VOICE_USER_CHANCE, Convert.toStr(userChance + 1));
            }
        }
        //userChance默认为0
        return VoiceVo.init(userInfo, path, 3 - userChance);
    }
}
